package design.masterWorker;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;

public class Worker implements Runnable{
    // 存放任务队列的引用
    private ConcurrentLinkedQueue<Task> taskQueue;
    // 存放Worker的处理结果Map
    private ConcurrentHashMap<String,Object> taskResultMap;

    public ConcurrentLinkedQueue<Task> getWorkQueue() {
        return taskQueue;
    }

    public void setWorkQueue(ConcurrentLinkedQueue<Task> workQueue) {
        this.taskQueue = workQueue;
    }

    public ConcurrentHashMap<String, Object> getTaskResultMap() {
        return taskResultMap;
    }

    public void setTaskResultMap(ConcurrentHashMap<String, Object> taskResultMap) {
        this.taskResultMap = taskResultMap;
    }

    @Override
    public void run() {
        while(true){
            // 取出一个任务队列中的任务
            Task task = this.taskQueue.poll();
            if(task == null){
                // 如果没有任务就退出
                break;
            }
            System.out.println("Worker = " + Thread.currentThread() + "-执行任务" + task.getId());
            // 调用任务处理
            Object output = handle(task);
            this.taskResultMap.put(Integer.toString(task.getId()),output);
        }
    }
    // 任务处理方法
    private Object handle(Task input){
        Object output = null;
        try {
            Thread.sleep(500);
            output = input.getPrice() + 1;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return output;
    }
}
